﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Threading;

namespace Rsdn.Humor.Collector
{
  public partial class MainWindow : Window
  {
    private DispatcherTimer _Timer;

    private void _OnTimer(object sender, EventArgs args)
    {
      var t10 = ResReqHelper.Statistics.GetTop10Info();
      this.top10List.ItemsSource = t10;
    }

    private void _ShowEndMsg()
    {
      MessageBox.Show("Humor collection completed", "!!", MessageBoxButton.OK, MessageBoxImage.Asterisk);
    }

    public MainWindow()
    {
      InitializeComponent();
      _Timer = new DispatcherTimer(new TimeSpan(0, 0, 1), DispatcherPriority.Normal, _OnTimer, Application.Current.Dispatcher);
      comboBox1.SelectedIndex = 1;
    }

    private void _OnError(ResReq sender, Uri url, Exception ex)
    {
      Action<ResReq, Uri, Exception> a = (s, u, e)=>
      {
        errorList.Items.Add(new KeyValuePair<string, Exception>(s.URL.AbsoluteUri, e));
      };
      if (!System.Windows.Application.Current.Dispatcher.CheckAccess())
        System.Windows.Application.Current.Dispatcher.BeginInvoke(a, DispatcherPriority.Normal, sender, url, ex);
      else
        a(sender, url, ex);
    }

    private void bStart_Click(object sender, RoutedEventArgs e)
    {
      ResReqHelper.ResDomain = new Uri("http://rsdn.ru/");
      ResReqHelper.TotalProgressed += (double pc) =>
      {
        Action<double> a = (p)=>
        {
          progressBar1.Value = Math.Min(100.0, Math.Max(0, pc));
          if (p >= 100)
              _ShowEndMsg();
        };
        if (!System.Windows.Application.Current.Dispatcher.CheckAccess())
          System.Windows.Application.Current.Dispatcher.BeginInvoke(a, DispatcherPriority.Normal, pc);
        else
          a(pc);
      };
      const int to = 120 * 1000;
      for (int i = 1; i < 30000; i += ResReqHelper.DefaultItemsInLists)
      {
        var lf = new ListFrame(string.Format(@"forum/MsgList.aspx?gid=33&start={0}&flat=1", i), 
                               Encoding.UTF8, 
                               to, 
                               null,
                               _OnError);

//        break;
      }
    }

    private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
      int max = int.Parse((string)((ComboBoxItem)comboBox1.SelectedItem).Tag);
      ThreadPool.SetMaxThreads(max, max/2);
    }

    private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
      try
      {
        ResReqHelper.SaveStat();
      }
      catch(Exception ex)
      {
        MessageBox.Show(ex.ToString(), "Ошибка сохранения данных", MessageBoxButton.OK, MessageBoxImage.Error);
        e.Cancel = true;
      }
    }

    private void bReset_Click(object sender, RoutedEventArgs e)
    {
      ResReqHelper.ResetStat();
    }

    private void top10List_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
      if(null !=top10List.SelectedItem)
      {
        ResId i = (ResId)top10List.SelectedItem;
        System.Diagnostics.Process.Start(i.ToString());
      }
    }
  }
}
